package com.eastfair.common.controller.micetother;

import cn.hutool.core.date.LocalDateTimeUtil;
import com.eastfair.common.consts.CrmConstants;
import com.eastfair.common.dto.*;
import com.eastfair.common.service.CrmPrjInfSyncService;
import com.eastfair.core.base.R;
import com.eastfair.core.context.ContextUtil;
import com.eastfair.core.exception.BizException;
import com.eastfair.venuebooking.api.ExhibitionFeign;
import com.eastfair.venuebooking.api.ServiceProviderFeign;
import com.eastfair.venuebooking.vo.ExhibitionVO;
import com.eastfair.venueservice.enumeration.ServiceProviderTypeEnum;
import com.eastfair.venueservice.vo.ExhibitionServiceProviderVO;
import core.handler.annotation.XxlJob;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.*;

/**
 * Crm同步项目任务.
 *
 * @author dqq
 * @date 2023 /2/13
 */
@Component
@Slf4j
public class CrmPrjInfSyncTask {

    public static final int LEN = 10;

    @Value("${com.eastfair.projectId}")
    private Long projectId;

    @Resource
    private CrmPrjInfSyncService crmPrjInfSyncService;

    @Resource
    private ExhibitionFeign exhibitionFeign;

    @Resource
    private ServiceProviderFeign serviceProviderFeign;

    /**
     * 按指定大小，分隔集合，将集合按规定个数分为n个部分
     *
     * @param <T>  the type parameter
     * @param list the list
     * @param len  the len
     * @return list
     */
    public static <T> List<List<T>> splitList(List<T> list, int len) {
        if (list == null || list.isEmpty() || len < 1) {
            return Collections.emptyList();
        }
        List<List<T>> result = new ArrayList<>();
        int size = list.size();
        int count = (size + len - 1) / len;
        for (int i = 0; i < count; i++) {
            List<T> subList = list.subList(i * len, (Math.min((i + 1) * len, size)));
            result.add(subList);
        }
        return result;
    }

    /**
     * Crm同步项目任务.
     */
    // @Scheduled(cron="0/10 * * * * *")
    @XxlJob("syncPrjInf")
    public void syncPrjInf() {
        log.info("syncPrjInf - Crm同步项目任务");
        ContextUtil.setProjectId(projectId);
        R<List<ExhibitionVO>> result = exhibitionFeign.queryNeedSyncExhibition();
        if (!result.getIsSuccess()) {
            throw BizException.wrap(result.getCode(), result.getMsg());
        }
        List<ExhibitionVO> list = result.getData();
        if (list == null || list.isEmpty()) {
            log.info("syncPrjInf - 没有待同步的展会信息");
            return;
        }
        List<List<ExhibitionVO>> lists = splitList(list, LEN);
        for (int i = 0; i < lists.size(); i++) {
            GmApiPrjInfDtos gmApiPrjInfDtos = new GmApiPrjInfDtos();
            List<GmApiPrjInfDto> dtos = new ArrayList<>();
            for (ExhibitionVO exhibitionVO : lists.get(i)) {
                GmApiPrjInfDto gmApiPrjInfDto = new GmApiPrjInfDto();
                gmApiPrjInfDto.setDelInd("0");
                gmApiPrjInfDto.setDtSrc(CrmConstants.DT_SRC);
                gmApiPrjInfDto.setEddt(Date.from(exhibitionVO.getExhibitionEndTime().atZone(ZoneId.systemDefault()).toInstant()));
                gmApiPrjInfDto.setLoadBtno(String.valueOf(i));
                gmApiPrjInfDto.setLoadTm(Date.from(LocalDateTime.now().atZone(ZoneId.systemDefault()).toInstant()));
                gmApiPrjInfDto.setPrjArea("无");
                gmApiPrjInfDto.setPrjAreaScop("无");
                gmApiPrjInfDto.setPrjCntnt("无");
                gmApiPrjInfDto.setPrjGrd("无");
                gmApiPrjInfDto.setPrjId(exhibitionVO.getId().toString());
                gmApiPrjInfDto.setPrjSt(exhibitionVO.getState().getDesc());
                gmApiPrjInfDto.setPrjTopc(exhibitionVO.getExhibitionNature().getDesc());
                gmApiPrjInfDto.setPrjTp(exhibitionVO.getExhibitionType().getDesc());
                gmApiPrjInfDto.setSttm(Date.from(exhibitionVO.getExhibitionStartTime().atZone(ZoneId.systemDefault()).toInstant()));
                gmApiPrjInfDto.setSuprPrjId("无");
                dtos.add(gmApiPrjInfDto);
            }
            gmApiPrjInfDtos.setDtos(dtos);
            crmPrjInfSyncService.syncPrjInf(gmApiPrjInfDtos);
        }
    }

    /**
     * 同步项目与主办方关系.
     */
    // @Scheduled(cron="0/10 * * * * *")
    @XxlJob("syncPrjAndHostRel")
    public void syncPrjAndHostRel() {
        log.info("syncPrjAndHostRel - 同步项目与主办方关系");
        ContextUtil.setProjectId(projectId);
        R<List<ExhibitionVO>> result = exhibitionFeign.queryNeedSyncExhibition();
        if (!result.getIsSuccess()) {
            throw BizException.wrap(result.getCode(), result.getMsg());
        }
        List<ExhibitionVO> list = result.getData();
        if (list == null || list.isEmpty()) {
            log.info("syncPrjInf - 没有待同步的项目与主办方信息");
            return;
        }
        List<List<ExhibitionVO>> lists = splitList(list, LEN);
        for (int i = 0; i < lists.size(); i++) {
            GmApiPrjAndHostRelDtos gmApiPrjAndHostRelDtos = new GmApiPrjAndHostRelDtos();
            List<GmApiPrjAndHostRelDto> dtos = new ArrayList<>();
            for (ExhibitionVO exhibitionVO : lists.get(i)) {
                if(Objects.nonNull(exhibitionVO.getCustomerId())){
                    GmApiPrjAndHostRelDto gmApiPrjAndHostRelDto = new GmApiPrjAndHostRelDto();
                    gmApiPrjAndHostRelDto.setDelInd("0");
                    gmApiPrjAndHostRelDto.setDtSrc(CrmConstants.DT_SRC);
                    gmApiPrjAndHostRelDto.setLoadBtno(String.valueOf(i));
                    gmApiPrjAndHostRelDto.setLoadTm(LocalDateTimeUtil.format(LocalDateTime.now(),"yyyy-MM-dd HH:mm:ss"));
                    gmApiPrjAndHostRelDto.setPrjAndSpsRelId(exhibitionVO.getId().toString());
                    gmApiPrjAndHostRelDto.setPrjId(exhibitionVO.getId().toString());
                    gmApiPrjAndHostRelDto.setSpsId(exhibitionVO.getCustomerId().toString());
                    gmApiPrjAndHostRelDto.setReTp("0019");
                    gmApiPrjAndHostRelDto.setCrdtTpcd(CrmConstants.CRDT_TPCD);
                    gmApiPrjAndHostRelDto.setCrdtNo(exhibitionVO.getUscc());
                    dtos.add(gmApiPrjAndHostRelDto);
                }
            }
            gmApiPrjAndHostRelDtos.setDtos(dtos);
            crmPrjInfSyncService.syncPrjAndHostRel(gmApiPrjAndHostRelDtos);
        }
    }

    /**
     * 同步项目与服务商关系.
     */
    // @Scheduled(cron="0/10 * * * * *")
    @XxlJob("syncPrjAndSvcRel")
    public void syncPrjAndSvcRel() {
        log.info("syncPrjAndSvcRel - 同步项目与服务商关系");
        ContextUtil.setProjectId(projectId);
        R<List<ExhibitionServiceProviderVO>> result = serviceProviderFeign.queryNeedSyncExhibitionProvider();
        if (!result.getIsSuccess()) {
            throw BizException.wrap(result.getCode(), result.getMsg());
        }
        List<ExhibitionServiceProviderVO> list = result.getData();
        if (list == null || list.isEmpty()) {
            log.info("syncPrjAndSvcRel - 没有待同步的项目与服务商关系");
            return;
        }
        List<List<ExhibitionServiceProviderVO>> lists = splitList(list, LEN);
        for (int i = 0; i < lists.size(); i++) {
            GmApiPrjAndSvcRelDtos gmApiPrjAndSvcRelDtos = new GmApiPrjAndSvcRelDtos();
            List<GmApiPrjAndSvcRelDto> dtos = new ArrayList<>();
            for (ExhibitionServiceProviderVO exhibitionServiceProviderVO : lists.get(i)) {
                GmApiPrjAndSvcRelDto gmApiPrjAndSvcRelDto = new GmApiPrjAndSvcRelDto();
                gmApiPrjAndSvcRelDto.setCrdtNo(exhibitionServiceProviderVO.getUscc());
                gmApiPrjAndSvcRelDto.setCrdtTpcd(CrmConstants.CRDT_TPCD);
                gmApiPrjAndSvcRelDto.setDelInd("0");
                gmApiPrjAndSvcRelDto.setDtSrc(CrmConstants.DT_SRC);
                if(Objects.nonNull(exhibitionServiceProviderVO.getValidEndTime())){
                    gmApiPrjAndSvcRelDto.setEddt(exhibitionServiceProviderVO.getValidEndTime().toLocalDate().toString());
                }
                gmApiPrjAndSvcRelDto.setLoadBtno(String.valueOf(i));
                gmApiPrjAndSvcRelDto.setLoadTm(LocalDateTimeUtil.format(LocalDateTime.now(), "yyyy-MM-dd HH:mm:ss"));
                gmApiPrjAndSvcRelDto.setPrjAndSvcpvdrRelId(exhibitionServiceProviderVO.getId().toString());
                gmApiPrjAndSvcRelDto.setPrjId(exhibitionServiceProviderVO.getVbExhibitionId().toString());
                gmApiPrjAndSvcRelDto.setSttm(LocalDate.now().toString());
                gmApiPrjAndSvcRelDto.setSvcpvdrId(exhibitionServiceProviderVO.getServiceProviderId().toString());
                if(exhibitionServiceProviderVO.getServiceProviderType().equals(ServiceProviderTypeEnum.MAIN_TRANSPORT_SERVICE_PROVIDER.getCode())){
                    gmApiPrjAndSvcRelDto.setSvcpvdrTp("2");
                }else if(exhibitionServiceProviderVO.getServiceProviderType().equals(ServiceProviderTypeEnum.BUILD_SERVICE_PROVIDER.getCode())){
                    gmApiPrjAndSvcRelDto.setSvcpvdrTp("1");
                }else {
                    gmApiPrjAndSvcRelDto.setSvcpvdrTp("0");
                }
                dtos.add(gmApiPrjAndSvcRelDto);
            }
            gmApiPrjAndSvcRelDtos.setDtos(dtos);
            crmPrjInfSyncService.syncPrjAndSvcRel(gmApiPrjAndSvcRelDtos);
        }
    }
}